//
//  FWPageEmojiLayout.swift
//  DBS
//
//  Created by 王方伟 on 2017/4/24.
//  Copyright © 2017年 wfw. All rights reserved.
//

import UIKit

class FWPageEmojiLayout: UICollectionViewFlowLayout {
    var colCount : Int = 4
    var rowCount : Int = 2
    fileprivate lazy var attrsArray : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
    fileprivate var contentWidth : CGFloat = 0
    fileprivate var startIndex = 0
}

extension FWPageEmojiLayout {
    override func prepare() {
        let itemW = (collectionView!.bounds.width - sectionInset.left - sectionInset.right - minimumInteritemSpacing * CGFloat(colCount - 1)) / CGFloat(colCount)
        let itemH = (collectionView!.bounds.height - sectionInset.top - sectionInset.bottom - minimumLineSpacing * CGFloat(rowCount - 1)) / CGFloat(rowCount)
        
        let section = collectionView!.numberOfSections
        var prePageCount : Int = 0
        for i in startIndex..<section {
            let row = collectionView!.numberOfItems(inSection: i)
            for j in startIndex..<row {
                let indexPath = IndexPath(item: j, section: i)
                let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                let page = j / (colCount * rowCount)
                let index = j % (colCount * rowCount)
                
                let itemY = sectionInset.top + (itemH + minimumLineSpacing) * CGFloat((index / colCount))
                let itemX = CGFloat(prePageCount + page) * collectionView!.bounds.width + sectionInset.left + (itemW + minimumInteritemSpacing) * CGFloat(index % colCount)
                
                attrs.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
                attrsArray.append(attrs)
            }
            prePageCount += (row - 1) / (colCount * rowCount) + 1
        }
        contentWidth = CGFloat(prePageCount) * collectionView!.bounds.width
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return attrsArray
    }
    
    override var collectionViewContentSize: CGSize{
        return CGSize(width: contentWidth + sectionInset.left + sectionInset.right, height: 0)
    }
}
